package fi.jamk.ourcookingapp.backend.architecture.json;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;
import fi.jamk.ourcookingapp.backend.MyTools;


/**
 * Webservice for executing the GET action
 * Taken from http://stackoverflow.com/questions/19217835/can-an-android-app-connect-directly-to-an-online-mysql-database%22
 */
public class WebService extends AsyncTask<String,Void,JSONObject>{

	public static final String WEBSERVICE_URL = "http://student.labranet.jamk.fi/~H8145/webservice/index.php";
	public static final String DATASERVICE_URL = "http://student.labranet.jamk.fi/~H8145/data";

	@Override
	protected JSONObject doInBackground(String... args) {
		InputStream inputStream = null;
        String result = "";
        JSONObject json = null;
        
        try {
    		HttpClient httpClient = new DefaultHttpClient();
    		HttpGet httpGet = new HttpGet(genUrl(args));
			HttpResponse response = httpClient.execute(httpGet);
    		HttpEntity entity = response.getEntity();
    		inputStream = entity.getContent();
    	} catch (Exception e) {
    		Log.e("JSON", "Error in HTTP connection.");
    	}
        
    	try {
    		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"),8);
    		StringBuilder stringBuffer = new StringBuilder();
    		String line = null;
    		while ((line = reader.readLine()) != null) {
    			stringBuffer.append(line + "\n");
    		}
    		inputStream.close();
    		result = stringBuffer.toString();
    	} catch(Exception e){
    		Log.e("JSON", "Error converting result to string.");
    	}
    	
    	try {
        	json = new JSONObject(result);
		} catch (JSONException e) {
			Log.e("JSON", "Error parsing data.");
		}
        
        return json;
	}

	/**
	 * Encodes the given parameters
	 * @param args
	 * @return encoded url
	 */
	private String genUrl(String[] args) {
		String result = args[0];
		List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
		if(MyTools.isEmpty(args[1])){
			return result;
		}
		String tmp[] = args[1].split("&");
		for (String string : tmp) {
			String spli[] = string.split("=>");
			params.add(new BasicNameValuePair(spli[0], spli[1]));
		}
		String paramString = URLEncodedUtils.format(params, "utf-8");
		return result + paramString;
	}
	
	/**
	 * Executes the GET action
	 * @param getData
	 * @param controller
	 * @param action
	 * @return JSONObject
	 */
	public AsyncTask<String, Void, JSONObject> execute(String getData, String controller, String action) {
		return super.execute(WEBSERVICE_URL + "/" + controller + "/" + action + "?", getData);
	}

	
}